package com.loren.demo14.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.loren.demo14.dto.UserAuthDto;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@AllArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        // SpringSecurity提供的获得登录用户的信息
        UserAuthDto userAuthDto = (UserAuthDto) authentication.getPrincipal();
        // 生成token
        String token = UUID.randomUUID().toString().replace("-", "");
        // 将UserAuthDto转为json字符串存进redis，key = token
        String tokenValue = this.objectMapper.writeValueAsString(userAuthDto);
        this.stringRedisTemplate.opsForValue().set(token, tokenValue, 7200L, TimeUnit.SECONDS);
        // 将token返回给前端
        response.getWriter().write(this.objectMapper.writeValueAsString(token));
    }
}